package com.wangxiaonan.process.config;

import com.wangxiaonan.process.plugin.directive.SQLDirective;
import com.wangxiaonan.process.plugin.method.BlankMethod;
import freemarker.cache.MruCacheStorage;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Custom FreeMarker Configurer
 *
 * @Author: wangxiaonan
 * @Date: 2019/2/27
 **/
@Configuration
public class FreeMarkerConfig {

    private static final String TEMPLATE_BASE_PATH = "/template/";

    @Bean("fkConfiguration")
    public static freemarker.template.Configuration initFreeMarkerConfiguration() {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(
                freemarker.template.Configuration.VERSION_2_3_28);
        cfg.setTagSyntax(
                freemarker.template.Configuration.SQUARE_BRACKET_TAG_SYNTAX);// For example [#if x][@foo /][/#if].

        // Specify the source where the template files come from.
        cfg.setClassForTemplateLoading(FreeMarkerConfig.class, TEMPLATE_BASE_PATH);

        // Set the preferred charset template files are stored in. UTF-8 is
        // a good choice in most applications:
        cfg.setDefaultEncoding("UTF-8");
        // Sets how errors will appear.
        // During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        // Don't log exceptions inside FreeMarker that it will thrown at you anyway:
        cfg.setLogTemplateExceptions(false);

        // Wrap unchecked exceptions thrown during template processing into TemplateException-s.
        cfg.setWrapUncheckedExceptions(true);

        // Creates a new MRU cache storage with specified maximum cache sizes.
        cfg.setCacheStorage(new MruCacheStorage(20, 250));

        // Adds a shared variable to the configuration.
        cfg.setSharedVariable("sql", new SQLDirective());
        cfg.setSharedVariable("isBlank", new BlankMethod());
        return cfg;
    }

}
